package com.delivery.deliverysystem.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.delivery.deliverysystem.common.DataSourceBean;
import com.delivery.deliverysystem.pojo.DAO.PdfDAO;
import com.delivery.deliverysystem.pojo.DAO.ProductPdfDAO;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.UnitValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PdfServiceImpl {

//    /**
//     * 生成PDF文件
//     * @param pdfDAO PDF内容
//     * @param type 格式类型（A4、二等分、三等分）
//     * @return PDF字节流
//     * @throws IOException
//     */
//    public static void generatePdf(PdfDAO pdfDAO, HttpServletResponse response, Integer type) throws IOException {
//        PdfWriter writer = new PdfWriter(response.getOutputStream());
//        PdfFont font = PdfFontFactory.createFont("STSong-Light","UniGB-UCS2-H");
//        PdfDocument pdfDocument = new PdfDocument(writer);
//        Document document = new Document(pdfDocument);
//        document.setFont(font);
//
//        switch (type) {
//            //A4格式
//            case 1:
//                generateA4Pdf(pdfDAO, document);
//                break;
//            //二等分格式
//            case 2:
//                document.setTopMargin(10);
//                pdfDocument.setDefaultPageSize(new PageSize(PageSize.A4.getWidth(), PageSize.A4.getHeight() / 2));
//                generateHalfPdf(pdfDAO, document);
//                break;
//            //三等分格式
//            case 3:
//                document.setTopMargin(10);
//                pdfDocument.setDefaultPageSize(new PageSize(PageSize.A4.getWidth(), PageSize.A4.getHeight() / 3));
//                generateThirdPdf(pdfDAO, document);
//                break;
//            default:
//                throw new IllegalArgumentException("Unsupported format: " + type);
//        }
//
//        document.close();
//    }
    @Autowired
    private DataSourceBean dataSourceBean;
    @Value("${server.port}")
    private Integer port;

    public ResponseEntity<Map<String, String>> generatePdf(PdfDAO pdfDAO, HttpServletResponse response, Integer type) throws Exception {


        // 准备数据源
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("pdfDAO", pdfDAO);

        // 设置数据源
        List<Map<String, Object>> reportData = dataSourceBean.loadPdfData("dataSourceName", "dataSetName", parameters);

        // 根据type选择模板
        String templateName;
        String loadUrl = "http://localhost:"+port+"/ureport/preview?_u=file:";
        String designUrl = "http://localhost:"+port+"/ureport/designer?_u=file:";
        String filename = pdfDAO.getFullName() +pdfDAO.getDeliveryDate() + "送货单";
        Map<String, String> urls = new HashMap<>();
        switch (type) {
            case 1:
                templateName = "A4送货单报表.ureport.xml";
                urls.put("预览前下载：", loadUrl + templateName + "&_n="+filename);
                urls.put("设计格式：", designUrl + templateName + "&_n="+filename);
                break;
            case 2:
                templateName = "二等分A4送货单报表.ureport.xml";
                urls.put("预览前下载：", loadUrl + templateName+ "&_n="+filename);
                urls.put("设计格式：", designUrl + templateName+ "&_n="+filename);
                break;
            case 3:
                templateName = "三等分A4送货单报表.ureport.xml";
                urls.put("预览前下载：", loadUrl + templateName+ "&_n="+filename);
                urls.put("设计格式：", designUrl + templateName+ "&_n="+filename);
                break;
            default:
                throw new IllegalArgumentException("暂时没有该类型: " + type);
        }
        return ResponseEntity.ok(urls);
    }
    private static Map<String, Object> convertPdfDaoToDataMap(PdfDAO pdfDAO) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("fullName", pdfDAO.getFullName());
        dataMap.put("address", pdfDAO.getAddress());
        dataMap.put("companyPhone", pdfDAO.getCompanyPhone());
        dataMap.put("companyFax", pdfDAO.getCompanyFax());
        dataMap.put("clientName", pdfDAO.getClientName());
        dataMap.put("clientAddress", pdfDAO.getClientAddress());
        dataMap.put("deliveryId", pdfDAO.getDeliveryId());
        dataMap.put("department", pdfDAO.getDepartment());
        dataMap.put("clientPhone", pdfDAO.getClientPhone());
        dataMap.put("username", pdfDAO.getUsername());
        dataMap.put("deliveryDate", pdfDAO.getDeliveryDate());
        dataMap.put("contact", pdfDAO.getContact());
        dataMap.put("products", pdfDAO.getProductPdfDAO());
        return dataMap;
    }

    /**
     * 生成A4格式的PDF
     * @param pdfDAO 内容
     * @param document 文档
     */
    private static void generateA4Pdf(PdfDAO pdfDAO, Document document) throws MalformedURLException {
        Table headerTable = new Table(UnitValue.createPercentArray(new float[]{20, 60, 20}));
        headerTable.setWidth(UnitValue.createPercentValue(100));
        headerTable.setMarginTop(10);
        //添加公司信息
        Image image = new Image(ImageDataFactory.create(pdfDAO.getCompanyLogo()));
        image.scaleAbsolute(80, 80); // 将图片放大到80x80的尺寸
        Cell companyLogoCell = new Cell().add(image);
        companyLogoCell.setHorizontalAlignment(HorizontalAlignment.LEFT);
        companyLogoCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(companyLogoCell);
        Cell companyInfoCell = new Cell();
        companyInfoCell.add(new Paragraph(pdfDAO.getFullName()).setBold().setFontSize(25));
        companyInfoCell.add(new Paragraph(pdfDAO.getAddress()).setBold());
        //TEL和FAX并排显示
        Table t1 = new Table(UnitValue.createPercentArray(new float[]{50, 50}));
        t1.setWidth(UnitValue.createPercentValue(100));
        t1.addCell(new Cell().add(new Paragraph("TEL：" + pdfDAO.getCompanyPhone()).setBold()).setBorder(Border.NO_BORDER));
        t1.addCell(new Cell().add(new Paragraph("FAX：" + pdfDAO.getCompanyFax()).setBold()).setBorder(Border.NO_BORDER));
        companyInfoCell.add(t1);
        companyInfoCell.setHorizontalAlignment(HorizontalAlignment.CENTER);
        companyInfoCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(companyInfoCell);
        Cell deliveryInfoCell = new Cell().add(new Paragraph("[ 送货单 ]").setBold().setFontSize(20)).add(new Paragraph("NO.: " + "00071499").setBold().setFontSize(14));
        deliveryInfoCell.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        deliveryInfoCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(deliveryInfoCell);
        document.add(headerTable);
        //添加客户信息
        // 创建一个表格来控制布局（3列：50% / 25% / 25%）
        Table infoTable = new Table(UnitValue.createPercentArray(new float[]{50, 25, 25}));
        infoTable.setWidth(UnitValue.createPercentValue(100));

        // 客户名称
        Cell cell1 = new Cell();
        cell1.add(new Paragraph("客户名称："+pdfDAO.getClientName()));
        cell1.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable.addCell(cell1);

        // 订单号
        Cell cell2 = new Cell();
        cell2.add(new Paragraph("订单号："+pdfDAO.getDeliveryId()));
        cell2.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable.addCell(cell2);

        // 制单人员
        Cell cell3 = new Cell();
        cell3.add(new Paragraph("制单人员："+pdfDAO.getUsername()));
        cell3.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable.addCell(cell3);

        // 添加表格到文档
        document.add(infoTable);

        // ---- 第二行的信息 ----
        Table infoTable2 = new Table(UnitValue.createPercentArray(new float[]{50, 25, 25}));
        infoTable2.setWidth(UnitValue.createPercentValue(100));

        // 客户地址
        Cell cell4 = new Cell();
        cell4.add(new Paragraph("客户地址："+pdfDAO.getClientAddress()));
        cell4.setBorder(Border.NO_BORDER);
        infoTable2.addCell(cell4);

        // 部门
        Cell cell5 = new Cell();
        cell5.add(new Paragraph("部门："+pdfDAO.getDepartment()));
        cell5.setBorder(Border.NO_BORDER);
        infoTable2.addCell(cell5);

        // 送货日期
        Cell cell6 = new Cell();
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd ");
        String formattedDateTime = currentDateTime.format(formatter);
        cell6.add(new Paragraph("送货日期："+formattedDateTime));
        cell6.setBorder(Border.NO_BORDER);
        infoTable2.addCell(cell6);

        // 添加第二行表格到文档
        document.add(infoTable2);
        //表格信息
        Table table = new Table(UnitValue.createPercentArray(new float[]{20, 20, 15, 8, 10, 10, 10,17}));
        table.setWidth(UnitValue.createPercentValue(100));
        String[] headers = {"物料代码", "品名/规格", "档号", "单位", "数量", "单价", "金额", "备注"};
        for (String header : headers) {
            Cell headerCell = new Cell().add(new Paragraph(header).setBold());
            table.addHeaderCell(headerCell);
        }
        Integer totalQuantity = 0;
        double  totalPrice = 0;
        double totalAmount = 0;
//        StringBuilder totalRemarks = new StringBuilder(); // 用于汇总所有remark信息
        for (ProductPdfDAO product : pdfDAO.getProductPdfDAO()) {
            table.addCell(product.getProductId());
            table.addCell(product.getProductName());
            table.addCell(product.getNumber());
            table.addCell(product.getUnit());
            table.addCell(String.valueOf(product.getTotal()));
            table.addCell(String.valueOf(product.getPrice()));
            double money = product.getTotal() * product.getPrice();
            table.addCell(String.valueOf(money));
            table.addCell(String.valueOf(product.getRemark()));
            // 计算总和
            totalQuantity += product.getTotal();
            totalPrice += product.getPrice();
            totalAmount += money;
//            totalRemarks.append(product.getRemark()).append("; ");
        }
        // 添加表格最后一行，合并前四个单元格
        Cell mergedCell = new Cell(1, 4).add(new Paragraph("")); // 创建一个合并了前四个单元格的Cell
        mergedCell.setHorizontalAlignment(HorizontalAlignment.CENTER); // 设置水平对齐方式
        table.addCell(mergedCell);

        // 添加汇总数据
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalQuantity))));
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalPrice))));
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalAmount))));
        table.addCell(new Cell().add(new Paragraph("")));
//        String remarksSummary = totalRemarks.length() > 0 ? totalRemarks.substring(0, totalRemarks.length() - 2) : "";
//        table.addCell(new Cell().add(new Paragraph(remarksSummary)));
        document.add(table);

        // 尾部信息
        Table infoTable3 = new Table(UnitValue.createPercentArray(new float[]{50, 50}));
        infoTable3.setWidth(UnitValue.createPercentValue(100));
        Cell cell7 = new Cell();
        cell7.add(new Paragraph("送货单位及经手人（盖章）:"));
        cell7.setBorder(Border.NO_BORDER);
        infoTable3.addCell(cell7);
        Cell cell8 = new Cell();
        cell8.add(new Paragraph("收货单位及经手人（盖章）:"));
        cell8.setBorder(Border.NO_BORDER);
        infoTable3.addCell(cell8);
        document.add(infoTable3);
    }

    /**
     * 生成二等分格式的PDF
     * @param pdfDAO 内容
     * @param document 文档
     */
    private static void generateHalfPdf(PdfDAO pdfDAO, Document document) {
        Table headerTable = new Table(UnitValue.createPercentArray(new float[]{70, 30}));
        headerTable.setWidth(UnitValue.createPercentValue(100));
        headerTable.setMarginTop(3);
        //添加公司信息
        Cell companyInfoCell = new Cell();
        companyInfoCell.add(new Paragraph(pdfDAO.getFullName()).setBold().setFontSize(22));
        companyInfoCell.add(new Paragraph(pdfDAO.getAddress()).setBold());
        //TEL和FAX并排显示
        Table t1 = new Table(UnitValue.createPercentArray(new float[]{50, 50}));
        t1.setWidth(UnitValue.createPercentValue(100));
        t1.addCell(new Cell().add(new Paragraph("TEL：" + pdfDAO.getCompanyPhone()).setBold()).setFontSize(12).setBorder(Border.NO_BORDER));
        t1.addCell(new Cell().add(new Paragraph("FAX：" + pdfDAO.getCompanyFax()).setBold()).setFontSize(12).setBorder(Border.NO_BORDER));
        companyInfoCell.add(t1);
        companyInfoCell.setHorizontalAlignment(HorizontalAlignment.LEFT);
        companyInfoCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(companyInfoCell);
        Cell deliveryInfoCell = new Cell().add(new Paragraph("[ 送货单 ]").setBold().setFontSize(18)).add(new Paragraph("NO.: " + "00071499").setBold().setFontSize(13));
        deliveryInfoCell.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        deliveryInfoCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(deliveryInfoCell);
        document.add(headerTable);
        //添加客户信息
        // 创建一个表格来控制布局（3列：50% / 25% / 25%）
        Table infoTable = new Table(UnitValue.createPercentArray(new float[]{50, 25, 25}));
        infoTable.setWidth(UnitValue.createPercentValue(100));

        // 客户名称
        Cell cell1 = new Cell();
        cell1.add(new Paragraph("客户名称："+pdfDAO.getClientName()).setBold().setFontSize(12));
        cell1.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable.addCell(cell1);

        // 订单号
        Cell cell2 = new Cell();
        cell2.add(new Paragraph("联系人："+pdfDAO.getContact()).setBold().setFontSize(12));
        cell2.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable.addCell(cell2);

        // 制单人员
        Cell cell3 = new Cell();
        cell3.add(new Paragraph("制单人员："+pdfDAO.getUsername()).setBold().setFontSize(12));
        cell3.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable.addCell(cell3);

        // 添加表格到文档
        document.add(infoTable);

        // ---- 第二行的信息 ----
        Table infoTable2 = new Table(UnitValue.createPercentArray(new float[]{50, 25, 25}));
        infoTable2.setWidth(UnitValue.createPercentValue(100));

        // 客户地址
        Cell cell4 = new Cell();
        cell4.add(new Paragraph("客户地址："+pdfDAO.getClientAddress()).setBold().setFontSize(12));
        cell4.setBorder(Border.NO_BORDER);
        infoTable2.addCell(cell4);

        // 部门
        Cell cell5 = new Cell();
        cell5.add(new Paragraph("客户电话："+pdfDAO.getClientPhone()).setBold().setFontSize(12));
        cell5.setBorder(Border.NO_BORDER);
        infoTable2.addCell(cell5);

        // 送货日期
        Cell cell6 = new Cell();
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd ");
        String formattedDateTime = currentDateTime.format(formatter);
        cell6.add(new Paragraph("送货日期："+formattedDateTime).setBold().setFontSize(12));
        cell6.setBorder(Border.NO_BORDER);
        infoTable2.addCell(cell6);

        // 添加第二行表格到文档
        document.add(infoTable2);
        //表格信息
        Table table = new Table(UnitValue.createPercentArray(new float[]{23, 20, 10, 10, 10, 10,17}));
        table.setWidth(UnitValue.createPercentValue(100));
        String[] headers = {"品名/规格", "档号", "单位", "数量", "单价", "金额", "备注"};
        for (String header : headers) {
            Cell headerCell = new Cell().add(new Paragraph(header).setBold().setFontSize(12));
            table.addHeaderCell(headerCell);
        }
        Integer totalQuantity = 0;
        double  totalPrice = 0;
        double totalAmount = 0;
//        StringBuilder totalRemarks = new StringBuilder(); // 用于汇总所有remark信息
        for (ProductPdfDAO product : pdfDAO.getProductPdfDAO()) {
            table.addCell(product.getProductName()).setBold().setFontSize(12);
            table.addCell(product.getNumber()).setBold().setFontSize(12);
            table.addCell(product.getUnit()).setBold().setFontSize(12);
            table.addCell(String.valueOf(product.getTotal())).setBold().setFontSize(12);
            table.addCell(String.valueOf(product.getPrice())).setBold().setFontSize(12);
            double money = product.getTotal() * product.getPrice();
            table.addCell(String.valueOf(money)).setBold().setFontSize(12);
            table.addCell(String.valueOf(product.getRemark())).setBold().setFontSize(12);
            // 计算总和
            totalQuantity += product.getTotal();
            totalPrice += product.getPrice();
            totalAmount += money;
//            totalRemarks.append(product.getRemark()).append("; ");
        }
        // 添加表格最后一行，合并前四个单元格
        Cell mergedCell = new Cell(1, 3).add(new Paragraph("")); // 创建一个合并了前三个单元格的Cell
        mergedCell.setHorizontalAlignment(HorizontalAlignment.CENTER); // 设置水平对齐方式
        table.addCell(mergedCell);

        // 添加汇总数据
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalQuantity))).setBold()).setFontSize(12);
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalPrice))).setBold()).setFontSize(12);
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalAmount))).setBold()).setFontSize(12);
        table.addCell(new Cell().add(new Paragraph("")).setBold());
//        String remarksSummary = totalRemarks.length() > 0 ? totalRemarks.substring(0, totalRemarks.length() - 2) : "";
//        table.addCell(new Cell().add(new Paragraph(remarksSummary)));
        document.add(table);

        // 尾部信息
        document.add(new Paragraph("注：所送货物验收无误签单后，如有错误或质量问题，请于3天内通知本公司，过期概不负责，多谢合作！").setFontSize(10));
        Table infoTable3 = new Table(UnitValue.createPercentArray(new float[]{50, 50}));
        infoTable3.setWidth(UnitValue.createPercentValue(100));
        Cell cell7 = new Cell();
        cell7.add(new Paragraph("送货单位及经手人（盖章）:").setFontSize(10));
        cell7.setBorder(Border.NO_BORDER);
        infoTable3.addCell(cell7);
        Cell cell8 = new Cell();
        cell8.add(new Paragraph("收货单位及经手人（盖章）:").setFontSize(10));
        cell8.setBorder(Border.NO_BORDER);
        infoTable3.addCell(cell8);
        document.add(infoTable3);
    }

    /**
     * 生成三等分格式的PDF
     * @param pdfDAO 内容
     * @param document 文档
     */
    private static void generateThirdPdf(PdfDAO pdfDAO, Document document) {
        Table headerTable = new Table(UnitValue.createPercentArray(new float[]{25, 50, 25}));
        headerTable.setWidth(UnitValue.createPercentValue(100));
        //添加公司信息
        Cell bankCell = new Cell();
        bankCell.add(new Paragraph(""));
        bankCell.setHorizontalAlignment(HorizontalAlignment.LEFT);
        bankCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(bankCell);
        Cell companyInfoCell = new Cell();
        companyInfoCell.add(new Paragraph(pdfDAO.getFullName()).setBold().setFontSize(21));
        companyInfoCell.setHorizontalAlignment(HorizontalAlignment.CENTER);
        companyInfoCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(companyInfoCell);
        Cell deliveryInfoCell = new Cell().add(new Paragraph("NO.: " + "00071499").setBold().setFontSize(12));
        deliveryInfoCell.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        deliveryInfoCell.setBorder(Border.NO_BORDER); // 去掉边框
        headerTable.addCell(deliveryInfoCell);
        document.add(headerTable);

        Table infoTable1 = new Table(UnitValue.createPercentArray(new float[]{55, 22.5F,22.5F}));
        infoTable1.setWidth(UnitValue.createPercentValue(100));
        Cell cell = new Cell();
        cell.add(new Paragraph(pdfDAO.getAddress()).setFontSize(10));
        cell.setHorizontalAlignment(HorizontalAlignment.LEFT);
        cell.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable1.addCell(cell);
        Cell c1 = new Cell();
        c1.add(new Paragraph("TEL：" + pdfDAO.getCompanyPhone()).setFontSize(10));
        c1.setHorizontalAlignment(HorizontalAlignment.CENTER);
        c1.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable1.addCell(c1);
        Cell c2 = new Cell();
        c2.add(new Paragraph("FAX：" + pdfDAO.getCompanyFax()).setFontSize(10));
        c2.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        c2.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable1.addCell(c2);
        document.add(infoTable1);

        //添加客户信息
        // 创建一个表格来控制布局（3列：50% / 25% / 25%）
        Table infoTable = new Table(UnitValue.createPercentArray(new float[]{65,35}));
        infoTable.setWidth(UnitValue.createPercentValue(100));
        // 客户名称
        Cell cell1 = new Cell();
        cell1.add(new Paragraph("客户名称："+pdfDAO.getClientName()).setFontSize(12));
        cell1.setBorder(Border.NO_BORDER); // 去掉边框
        infoTable.addCell(cell1);
        // 送货日期
        Cell cell2 = new Cell();
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd ");
        String formattedDateTime = currentDateTime.format(formatter);
        cell2.add(new Paragraph("送货日期："+formattedDateTime).setFontSize(12));
        cell2.setBorder(Border.NO_BORDER);
        infoTable.addCell(cell2);
        // 添加表格到文档
        document.add(infoTable);

        //表格信息
        Table table = new Table(UnitValue.createPercentArray(new float[]{35, 12, 12, 12, 12, 17}));
        table.setWidth(UnitValue.createPercentValue(100));
        String[] headers = {"名称及规格", "单位", "数量", "单价", "金额", "备注"};
        for (String header : headers) {
            Cell headerCell = new Cell().add(new Paragraph(header)).setFontSize(10);
            table.addHeaderCell(headerCell);
        }
        Integer totalQuantity = 0;
        double  totalPrice = 0;
        double totalAmount = 0;
//        StringBuilder totalRemarks = new StringBuilder(); // 用于汇总所有remark信息
        for (ProductPdfDAO product : pdfDAO.getProductPdfDAO()) {
            table.addCell(product.getProductName()).setFontSize(10);
            table.addCell(product.getUnit()).setFontSize(10);
            table.addCell(String.valueOf(product.getTotal())).setFontSize(10);
            table.addCell(String.valueOf(product.getPrice())).setFontSize(10);
            double money = product.getTotal() * product.getPrice();
            table.addCell(String.valueOf(money)).setFontSize(10);
            table.addCell(String.valueOf(product.getRemark())).setFontSize(10);
            // 计算总和
            totalQuantity += product.getTotal();
            totalPrice += product.getPrice();
            totalAmount += money;
//            totalRemarks.append(product.getRemark()).append("; ");
        }
        // 添加表格最后一行，合并前四个单元格
        Cell mergedCell = new Cell(1, 2).add(new Paragraph("")); // 创建一个合并了前四个单元格的Cell
        mergedCell.setHorizontalAlignment(HorizontalAlignment.CENTER); // 设置水平对齐方式
        table.addCell(mergedCell);

        // 添加汇总数据
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalQuantity))));
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalPrice))));
        table.addCell(new Cell().add(new Paragraph(String.valueOf(totalAmount))));
        table.addCell(new Cell().add(new Paragraph("")));
//        String remarksSummary = totalRemarks.length() > 0 ? totalRemarks.substring(0, totalRemarks.length() - 2) : "";
//        table.addCell(new Cell().add(new Paragraph(remarksSummary)));
        document.add(table);


        // 尾部信息
        Table infoTable3 = new Table(UnitValue.createPercentArray(new float[]{50, 50}));
        infoTable3.setWidth(UnitValue.createPercentValue(100));
        Cell cell7 = new Cell();
        cell7.add(new Paragraph("制单人:"+pdfDAO.getUsername()).setFontSize(10));
        cell7.setBorder(Border.NO_BORDER);
        infoTable3.addCell(cell7);
        Cell cell8 = new Cell();
        cell8.add(new Paragraph("收货单位及经手人盖章:").setFontSize(10));
        cell8.setBorder(Border.NO_BORDER);
        infoTable3.addCell(cell8);
        document.add(infoTable3);
    }
}
